<script setup lang="ts">
import Pubsub from "pubsub-js"
import { onMounted, ref } from "vue"
import { LazyImg, Waterfall } from "vue-waterfall-plugin-next"
import "vue-waterfall-plugin-next/dist/style.css"
import useCover from "../useCover"
import Content from "./content.vue"

const waterfall = ref(null)
const plazaInfoRef = ref<any>(null)
const { loading, sameLoading, initCoverDataList, handleCreateTheSame, plazaList, pageCount, pagination } = useCover()

const init = async () => {
  try {
    const list = await initCoverDataList("plaza")
    plazaList.value = list
  } catch (error) {
    console.error(error)
  }
}

onMounted(async () => {
  await init()
  Pubsub.subscribe("UPDATE-SHINEE", async () => {
    await init()
    if (waterfall && waterfall.value) {
      //@ts-ignore
      waterfall.value.renderer()
    }
  })
})

const handleScroll = async () => {
  if (pagination.value.page >= pageCount.value) return
  const container = plazaInfoRef.value as HTMLDivElement
  // 计算滚动位置
  const scrollPosition = container.scrollHeight - container.scrollTop - container.clientHeight
  if (scrollPosition < 100) {
    pagination.value.page += 1
    const list = await initCoverDataList("plaza")
    plazaList.value = plazaList.value.concat(list)
  }
}
</script>

<template>
  <Content class="plaza-info" v-loading="loading">
    <template #title>
      <div class="title">AI·绘画广场</div>
    </template>
    <div
      v-if="plazaList.length > 0"
      style="height: 100vh; overflow-y: scroll"
      class="plaza"
      ref="plazaInfoRef"
      @scroll="handleScroll"
    >
      <Waterfall
        ref="waterfall"
        @scroll="handleScroll"
        :crossOrigin="false"
        :list="plazaList"
        :breakpoints="{
          1000: { rowPerView: 2 },
          300: { rowPerView: 1 }
        }"
      >
        <template #item="{ item, url, index }">
          <div class="info">
            <!-- <img class="image" :src="url" alt=""> -->
            <LazyImg class="image" :url="url" :style="{ backgroundColor: 'var(--v3-body-bg-color)' }" />
            <el-button class="btn" :loading="sameLoading" @click="handleCreateTheSame(item.id)">创造同款</el-button>
          </div>
        </template>
      </Waterfall>
      <!-- <FlexScroll :disabled="pagination.page >= pageCount" :immediate="immediate" @scroll="() => nextPage('plaza')"> -->
      <!-- </FlexScroll> -->
    </div>

    <el-empty v-else description="暂无数据" />
  </Content>
</template>

<style lang="scss" scoped>
.plaza-info ::v-deep .title {
  margin-top: unset !important;
}

.plaza {
  width: 100%;

  &::-webkit-scrollbar {
    width: 0;
  }
}

.info {
  width: 100%;
  margin-bottom: 15px;

  .image {
    width: 100%;
    border-radius: 10px;
  }

  .btn {
    width: 100%;
    height: 40px;
    margin-top: 12px;
    background: var(--v3-body-bg-color);
    border: unset !important;
  }
}
</style>
